package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouAuthTokenDao;
import com.lagou.edu.feign.EmailFeignClient;
import com.lagou.edu.feign.UserFeignClient;
import com.lagou.edu.pojo.LagouAuthToken;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.util.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    private LagouAuthTokenDao lagouAuthTokenDao;

    @Autowired
    private EmailFeignClient emailFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Boolean getCode(String email) {
        Boolean registed = userFeignClient.isRegisted(email);
        //已经注册,需要返回给前端失败
        if (registed) {
            return false;
        }
        String code = CodeUtil.getCode();
        LagouAuthToken lagouAuthToken = new LagouAuthToken();
        lagouAuthToken.setEmail(email);
        lagouAuthToken.setCode(code);
        Date date = new Date();
        lagouAuthToken.setCreatetime(date);
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        instance.add(Calendar.MINUTE, 10);
        Date expireTime = instance.getTime();
        lagouAuthToken.setExpiretime(expireTime);
        lagouAuthTokenDao.save(lagouAuthToken);
        emailFeignClient.sendEmail(email, code);
        return true;
    }

    public Integer validateCode(String email, String code) {
        Date now = new Date();

        //获取到最新一条token数据
        Sort createTime = new Sort(Sort.Direction.DESC, "createtime");
        LagouAuthToken lagouAuthToken = new LagouAuthToken();
        lagouAuthToken.setEmail(email);
        Example<LagouAuthToken> example = Example.of(lagouAuthToken);
        List<LagouAuthToken> all = lagouAuthTokenDao.findAll(example, createTime);
        if (all != null && all.size() > 0) {
            LagouAuthToken rToken = all.get(0);
            //0正确1错误2超时
            if (rToken != null && code.equals(rToken.getCode())) {
                if (now.before(rToken.getExpiretime())) {
                    return 0;
                } else {
                    return 2;
                }
            } else {
                return 1;
            }
        } else {
            return 1;
        }
    }

}
